const { serverError } = require('../constant/error.type')
const { successData } = require('../utils/common')

const {
  createOrder,
  findAllOrder,
  updateOrder,
} = require('../service/order.service')

class OrderController {
  async create(ctx) {
    const { id: user_id } = ctx.state.user
    const { address_id, goods_info, total } = ctx.request.body
    const order_number = 'XZD' + Date.now()
    serverError.message = '创建订单失败'
    try {
      const res = await createOrder({
        user_id,
        address_id,
        goods_info,
        total,
        order_number,
      })
      ctx.body = res ? successData('创建订单成功', res) : serverError
    } catch (error) {
      console.error(serverError.message, error)
      return ctx.app.emit('error', serverError, ctx)
    }
  }

  async findAll(ctx) {
    const { pageNum = 1, pageSize = 10, status = 0 } = ctx.request.query
    serverError.message = '获取订单列表失败'
    try {
      const res = await findAllOrder(pageNum, pageSize, status)
      ctx.body = res ? successData('获取订单列表成功', res) : serverError
    } catch (error) {
      console.error(serverError.message, error)
      ctx.app.emit('error', serverError, ctx)
    }
  }

  async update(ctx) {
    const { id } = ctx.request.params
    const { status } = ctx.request.body
    serverError.message = '更新订单状态失败'
    try {
      const res = await updateOrder(id, status)
      ctx.body = res ? successData('更新订单状态成功', res) : serverError
    } catch (error) {
      console.error(serverError.message, error)
      ctx.app.emit('error', serverError, ctx)
    }
  }
}

module.exports = new OrderController()
